﻿#include "tcpclient.h"

TcpClient::TcpClient(QObject *parent)
    : QObject(parent)
{
    socket = std::make_unique<QTcpSocket>(this);
    connect(socket.get(), &QTcpSocket::connected, this, &TcpClient::onConnected);
    connect(socket.get(), &QTcpSocket::disconnected, this, &TcpClient::onDisconnected);
    connect(socket.get(), &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
    connect(socket.get(), &QTcpSocket::errorOccurred, this, &TcpClient::onError);
}

TcpClient::~TcpClient() {
    // 当TcpClient对象被销毁时，socket也会被自动销毁
}

void TcpClient::connectToServer(const QString &hostAddress, quint16 port) {
    socket->connectToHost(hostAddress, port);
}

void TcpClient::sendData(const QByteArray &data) {
    if (socket->state() == QAbstractSocket::ConnectedState) {
        socket->write(data);
    } else {
        qDebug() << "Not connected to server, cannot send data.";
    }
}

void TcpClient::onConnected() {
    qDebug() << "Connected to server!";
//    this->sendData();
    emit connectedToServer(); // 发射信号通知上层
}

void TcpClient::onDisconnected() {
    qDebug() << "Disconnected from server.";
    emit disconnectedFromServer(); // 发射信号通知上层
}

void TcpClient::onReadyRead() {
    QByteArray data = socket->readAll();
    qDebug() << "Received data:" << data;
    emit dataReceived(data); // 发射信号并传递接收到的数据
}

void TcpClient::onError(QAbstractSocket::SocketError error) {
    qDebug() << "Socket error:" << error;
    emit errorOccurred(error); // 发射信号并传递错误信息
    // 这里可以添加额外的错误处理逻辑，比如重连尝试
}
